package com.young.nyd.web;

import com.young.common.core.excel.ExcelExport;
import com.young.common.core.excel.ExcelImport;
import com.young.common.core.excel.IExcelExport;
import com.young.common.core.excel.IExcelImport;
import com.young.common.util.CommonUtil;
import com.young.common.util.Result;
import com.young.common.util.StringUtils;
import com.young.common.util.Page;
import com.young.interfaces.log.annotation.Log;
import com.young.nyd.model.UviEnvcontrol;
import com.young.nyd.service.IUviEnvcontrolService;
import com.young.nyd.util.XzquUserController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import static com.young.common.util.Result.buildFail;

/**
 * 环境风险管控服务
 * Created by hu on 2018-11-7.
 */
@Controller
@RequestMapping("/nyd/uviEnvcontrol")
public class UviEnvcontrolController {

    @Resource(name = "uviEnvcontrolService")
    IUviEnvcontrolService service;

    XzquUserController xzquUserController = new XzquUserController();

    /**
     * 获取数据列表
     *
     * @param obj
     * @param request
     * @return
     */
    @Log("查询环境风险管控列表")
    @RequestMapping("/getList")
    @ResponseBody
    public Object getList(UviEnvcontrol obj, HttpServletRequest request) {
        String xzbm = xzquUserController.selectUserXZBM();
        if(xzbm == null){
            return  Result.build(Result.CodeEnum.SESSION_TIMEOUT);
        }else if(xzbm.equals("root")){

        }else {
            obj.setRegions(xzbm);
        }
        List<UviEnvcontrol> list = service.getList(obj);
        return new Result(list);
    }

    /**
     * 获取分页数据
     *
     * @param obj
     * @param request
     * @return
     */
    @Log("分页查询环境风险管控列表")
    @RequestMapping("/getPage")
    @ResponseBody
    public Object getPage(UviEnvcontrol obj, HttpServletRequest request) {
        Page page = CommonUtil.getPageFromRequest(request);
        String xzbm = xzquUserController.selectUserXZBM();
        if(xzbm == null){
            return  Result.build(Result.CodeEnum.SESSION_TIMEOUT);
        }else if(xzbm.equals("root")){

        }else {
            obj.setRegions(xzbm);
        }
        List<UviEnvcontrol> list = service.getPage(obj, page);
        page.setData(list);
        return page;
    }

    /**
     * 获取单条数据
     *
     * @param id
     * @param request
     * @return
     */
    @Log("查询环境风险管控")
    @RequestMapping("/get")
    @ResponseBody
    public Object get(String id, HttpServletRequest request) {
        UviEnvcontrol obj = service.get(id);
        return new Result(obj);
    }

    /**
     * 统计数量
     *
     * @param obj
     * @param request
     * @return
     */
    @Log("统计环境风险管控数量")
    @RequestMapping("/count")
    @ResponseBody
    public Object count(UviEnvcontrol obj, HttpServletRequest request) {

        String xzbm = xzquUserController.selectUserXZBM();
        if(xzbm == null){
            return  Result.build(Result.CodeEnum.SESSION_TIMEOUT);
        }else if(xzbm.equals("root")){

        }else {
            obj.setRegions(xzbm);
        }
        return new Result(service.count(obj));
    }

    /**
     * 新增
     *
     * @param obj
     * @param request
     * @return
     */
    @Log("新增环境风险管控")
    @RequestMapping("/insert")
    @ResponseBody
    public Object insert(UviEnvcontrol obj, HttpServletRequest request) throws Exception {
        String countyCode = request.getParameter("county");
        String cityCode = request.getParameter("city");
        String provinceCode = request.getParameter("province");
        if (countyCode != null && !countyCode .equals("")){
            obj.setRegions(countyCode);
        }else if(cityCode != null && !cityCode .equals("")){
            obj.setRegions(cityCode);
        }else if(provinceCode != null && !provinceCode .equals("")){
            obj.setRegions(provinceCode);
        }else{
            return buildFail("行政区划为空");
        }
        obj.setId(CommonUtil.getUUID());
        service.insert(obj);
        return new Result();
    }

    /**
     * 修改
     *
     * @param obj
     * @param request
     * @return
     */
    @Log("修改环境风险管控")
    @RequestMapping("/update")
    @ResponseBody
    public Object update(UviEnvcontrol obj, HttpServletRequest request) {
        //获取是否锁定
        String unlock = obj.getUnlack();
        //判断unlock是否为空
        if (unlock != null) {
            //是否锁定（0：未锁定；1：已锁定）
            if (unlock.equals("0")) {
                //保存
                service.update(obj);
                return new Result();
            } else {
                return new Result(-1, "该信息已锁定，不能修改，如需修改，请联系省级用户！");
            }
        } else {
            return new Result(-1, "错误，请与管理员联系！");
        }
    }

    /**
     * 删除
     *
     * @param ids
     * @param id
     * @param request
     * @return
     */
    @Log("删除环境风险管控")
    @RequestMapping("/delete")
    @ResponseBody
    public Object delete(String ids, String id, HttpServletRequest request) {
        Result result = new Result();
        //是否有“,”
        int ishave = ids.indexOf(",");
        if (ishave == -1) {
            //获取复选框id
            UviEnvcontrol obj = service.get(ids);
            //判断是否为空
            if (obj.getUnlack() != null) {
                //是否为锁定（0：未锁定）
                if (obj.getUnlack().equals("0")) {
                    if (StringUtils.isNotBlank(ids)) {
                        String[] idArr = ids.split(",");
                        service.delete(idArr);
                    } else if (StringUtils.isNotBlank(id)) {
                        service.delete(id);
                    }
                    return new Result();
                } else {
                    return new Result(-1, "该信息已锁定，不能删除，如需解锁，请联系省级用户");
                }
            } else {
                return new Result(-1, "错误，请与管理员联系！");
            }
        } else {
            return new Result(-1, "请选择单条数据删除");
        }
    }

    /**
     * 导入
     *
     * @param file
     * @param request
     * @return
     */
    @Log("导入环境风险管控")
    @RequestMapping("/import")
    @ResponseBody
    public Object importExcel(MultipartFile file, HttpServletRequest request) {
        Result result = new Result();
        try {
            if (file != null && !file.isEmpty()) {
                //excel导入处理,返回excel中的数据集合
                IExcelImport ei = new ExcelImport(file);//将文件转为ExcelImport对象
                //从excel读取数据
                List<UviEnvcontrol> list = ei.getImportDataAsBean(UviEnvcontrol.class);
                if (list != null && list.size() > 0) {
                    int num = service.batchInsert(list);//批量插入
                    result.setInfo("成功导入数据" + num + "条!");
                } else {
                    result.setCode(-1);
                    result.setInfo("导入失败:excel解析后结果为空!");
                }
            } else {
                result.setCode(-1);
                result.setInfo("导入失败:文件为空!");
            }
        } catch (IOException e) {
            e.printStackTrace();
            result.setCode(-1);
            result.setInfo("导入失败!");
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
            result.setCode(-1);
            result.setInfo("导入失败!");
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(-1);
            result.setInfo("导入失败!");
        }
        return result;
    }

    /**
     * 导出
     *
     * @param obj      查询参数
     * @param request
     * @param response
     * @throws Exception
     */
    @Log("导出环境风险管控")
    @RequestMapping("/export")
    public void exportExcel(UviEnvcontrol obj, HttpServletRequest request, HttpServletResponse response, String ids) throws Exception {
        List<UviEnvcontrol> list = new ArrayList<UviEnvcontrol>();
        if (ids != null && !"".equals(ids)) {
            String[] ids1 = ids.split(",");
            for (String id : ids1) {
                UviEnvcontrol u = service.get(id);
                list.add(u);
            }
        } else {
            String xzbm = xzquUserController.selectUserXZBM();
            if(xzbm == null){
                response.getWriter().write("行政区划，数据为空!");
            }else if(xzbm.equals("root")){

            }else {
                obj.setRegions(xzbm);
            }
            list = service.getList(obj);
        }
        if (list != null && list.size() > 0) {
            IExcelExport ee = new ExcelExport();
            ee.insertBeanList(list, UviEnvcontrol.class);
            ee.write2Response(response, "环境风险管控" + System.currentTimeMillis() + ".xls");
        } else {
            response.getWriter().write("数据为空!");
        }
    }

    /**
     * 锁定
     *
     * @param ids
     * @param id
     * @param request
     * @return
     */
    @Log("锁定环境分析按管控表")
    @RequestMapping("/lock")
    @ResponseBody
    public Object lock(String ids, String id, HttpServletRequest request) {
        Result result = new Result();
        List<UviEnvcontrol> list = new ArrayList<UviEnvcontrol>();
        UviEnvcontrol envcontrol = new UviEnvcontrol();
        if (StringUtils.isNotBlank(ids)) {
            String[] idArr = ids.split(",");
            for (String st : idArr) {
                envcontrol.setId(st);
                envcontrol.setUnlack("1");
                service.update(envcontrol);

            }
        } else if (StringUtils.isNotBlank(id)) {
            service.update(envcontrol);
        } else {
            result.setCode(-1);
            result.setInfo("锁定失败:待锁定编号无效!");
        }
        return result;
    }

    /**
     * 解除锁定
     *
     * @param ids
     * @param id
     * @param request
     * @return
     */
    @Log("解除锁定环境风险管控表")
    @RequestMapping("/unlock")
    @ResponseBody
    public Object unlock(String ids, String id, HttpServletRequest request) {
        Result result = new Result();
        List<UviEnvcontrol> list = new ArrayList<UviEnvcontrol>();
        UviEnvcontrol envcontrol = new UviEnvcontrol();
        if (StringUtils.isNotBlank(ids)) {
            String[] idArr = ids.split(",");
            for (String st : idArr) {
                envcontrol.setId(st);
                envcontrol.setUnlack("0");
                service.update(envcontrol);

            }
        } else if (StringUtils.isNotBlank(id)) {
            service.update(envcontrol);
        } else {
            result.setCode(-1);
            result.setInfo("解除锁定失败:待锁定编号无效!");
        }
        return result;
    }

}